<template>
  <ych-modal
    :fullscreen="false"
    :title="title"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel">
    <template slot="footer">
      <a-button key="back" @click="handleCancel">{{ $t('m.common.button.close') }}</a-button>
      <a-button v-show="!disabled" key="submit" type="primary" @click="handleOk">{{ $t('m.common.button.ok') }}</a-button>
    </template>
    <a-form :form="form">
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :label="$t('m.bpm.entity.delegateBailee')">
        <a-input readOnly v-decorator="[ 'delegate', {rules: [
                    {
                      required: true,
                      message: '必填',
                    },
                  ]}]" @click="selectUser" placeholder="">
          <ych-icon slot="addonAfter" type="setting"/>
        </a-input>
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :label="$t('m.common.label.begin_time')"
        :hasFeedback="!disabled">
        <a-date-picker
          :disabled="disabled"
          :disabledDate="disabledStartDate"
          showTime
          placeholder=""
          format="YYYY-MM-DD HH:mm"
          @openChange="handleStartOpenChange"
          v-decorator="[ 'startTime', {rules: [
                    {
                      required: true,
                      message: '必填',
                    },
                  ]}]"
        />
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :label="$t('m.common.label.end_time')"
        :hasFeedback="!disabled">
        <a-date-picker
          :disabled="disabled"
          :disabledDate="disabledEndDate"
          showTime
          placeholder=""
          format="YYYY-MM-DD HH:mm"
          :open="endOpen"
          @openChange="handleEndOpenChange"
          v-decorator="[ 'endTime', {rules: [
                    {
                      required: true,
                      message: '必填',
                    },
                  ]}]"
        />
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :label="$t('m.bpm.entity.delegateResource')">
        <a-switch :disabled="disabled" :checkedChildren="$t('m.common.label.all')" :unCheckedChildren="$t('m.common.label.part')" v-model="model.resourceAll"/>
      </a-form-item>

    </a-form>

    <a-button-group v-show="!model.resourceAll && !disabled" style="margin-bottom: 8px;">
      <a-button icon="plus" @click="handleAddResource">{{ $t('m.common.button.add') }}</a-button>
    </a-button-group>
    <a-table
      v-show="!model.resourceAll"
      :columns="disabled ? columns2 : columns"
      rowKey="id"
      :dataSource="model.resourceList"
      bordered
      size="small"
    >
        <span slot="action" slot-scope="text, record">
          <a @click="handleDeleteResource(record)" v-show="!disabled">{{ $t('m.common.button.delete') }}</a>
        </span>
    </a-table>

    <Select-User-Tree-Modal ref="selectUserModal" @selectFinished="selectUserOK"></Select-User-Tree-Modal>
    <Select-Resource-Dialog ref="selectResourceDialog" @selectFinished="selectResourceOK"></Select-Resource-Dialog>
  </ych-modal>
</template>

<script>

  import moment from "moment";
  import {httpAction, getAction} from '@/api/manage';
  import SelectUserTreeModal from '../../../system/select/SelectUserTreeModal';
  import SelectResourceDialog from '../../select/SelectResourceDialog';
  import YchConstant from "@/api/YchConstant";

  export default {
    name: "DelegateModal",
    components: {
      SelectUserTreeModal,
      SelectResourceDialog
    },
    props: {},
    data() {
      return {
        model: {
          resourceAll: true,
          resourceList: []
        },
        disabled: false,
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        visible: false,
        title: this.$t('m.bpm.other.delegate_set_title'),
        endOpen: false,
        form: this.$form.createForm(this),
        url: {
          add: YchConstant.PREFIX_BPM + "/bpm-front/delegateTaskRest/addMyDelegateSetting/v1",
          edit: YchConstant.PREFIX_BPM + "/bpm-front/delegateTaskRest/editMyDelegateSetting/v1",
          getMyDelegateResourceList: YchConstant.PREFIX_BPM + "/bpm-front/delegateTaskRest/getMyDelegateResourceList/v1"
        },
        columns: [{
          title:this.$t('m.common.label.number'),
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        }, {
          title: this.$t('m.bpm.entity.delegateResourceName'),
          align: "center",
          width: 200,
          dataIndex: 'resourceName'
        }, {
          title: this.$t('m.common.label.operate'),
          dataIndex: 'action',
          align: "center",
          width: 120,
          scopedSlots: {customRender: 'action'},
        }],
        columns2: [{
          title:this.$t('m.common.label.number'),
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        }, {
          title: this.$t('m.bpm.entity.delegateResourceName'),
          align: "center",
          width: 200,
          dataIndex: 'resourceName'
        }]
      }
    },
    methods: {
      add() {
        this.edit({
          resourceAll: true,
          resourceList: []
        });
      },
      edit(record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.getMyDelegateResourceList();
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue({delegate: this.model.delegateName ? this.model.delegateName + '/' + this.model.delegateDeptName : null});
          this.form.setFieldsValue({startTime: this.model.startTime ? moment(this.model.startTime) : null});
          this.form.setFieldsValue({endTime: this.model.endTime ? moment(this.model.endTime) : null});
        });
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            if (!this.model.delegateId) {
              that.messageUtil.warning(this.$t('m.bpm.verify.tip_trusteeid_empty'));
              return;
            }
            if(values.startTime){
              values.startTime = values.startTime.format("YYYY-MM-DD HH:mm:ss")
            }
            if(values.endTime){
              values.endTime = values.endTime.format("YYYY-MM-DD HH:mm:ss")
            }
            let formData = Object.assign(this.model, values);
            if (this.model.resourceAll) {
              formData.resourceList = [];
            } else if (formData.resourceList.length == 0) {
              that.messageUtil.warning(this.$t('m.bpm.verify.tip_delegation_range_empty'));
              return;
            }
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.messageUtil.success(res.message);
                that.$emit('ok');
              } else {
                that.messageUtil.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      selectUser() {
        if (this.disabled) {
          return;
        }
        this.$refs.selectUserModal.visible = true;
      },
      selectUserOK(data, selectionRows) {
        if (selectionRows.length == 0) {
          return;
        }
        this.model.delegateId = selectionRows[0].userId;
        this.model.delegateName = selectionRows[0].realname;
        this.model.delegateDeptId = selectionRows[0].departId;
        this.model.delegateDeptName = selectionRows[0].departNameCurr;
        this.form.setFieldsValue({delegate: this.model.delegateName ? this.model.delegateName + '/' + this.model.delegateDeptName : null});
      },
      handleCancel() {
        this.close();
      },
      close() {
        this.visible = false;
      },
      disabledStartDate(startValue) {
        const endValue = this.form.getFieldValue("endTime");
        if (!startValue || !endValue) {
          return false;
        }
        return startValue.valueOf() > endValue.valueOf();
      },
      disabledEndDate(endValue) {
        const startValue = this.form.getFieldValue("startTime");
        if (!endValue || !startValue) {
          return false;
        }
        return startValue.valueOf() >= endValue.valueOf();
      },
      handleStartOpenChange(open) {
        if (!open) {
          this.endOpen = true;
        }
      },
      handleEndOpenChange(open) {
        this.endOpen = open;
      },
      getMyDelegateResourceList() {
        if (!this.model.id || this.model.resourceAll) {
          this.model.resourceList = [];
          return;
        }
        const that = this;
        that.confirmLoading = true;
        getAction(this.url.getMyDelegateResourceList, {parentId: this.model.id}).then((res) => {
          if (res.success) {
            that.model.resourceList = res.result;
          } else {
            that.messageUtil.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
        });
      },
      handleAddResource() {
        this.$refs.selectResourceDialog.radio = false;
        this.$refs.selectResourceDialog.visible = true;
      },
      selectResourceOK(data, selectionRows) {
        const that = this;
        let temp = [];
        that.model.resourceList.forEach(vo => {
          temp.push(vo.resourceId);
        });
        selectionRows.forEach(vo => {
          if (temp.indexOf(vo.id) != -1) {
            return;
          }
          that.model.resourceList.push({
            id: vo.id,
            resourceId: vo.id,
            resourceName: vo.name + '-V' + vo.version,
            type: '1',
          });
        });
      },
      handleDeleteResource(record) {
        this.model.resourceList.splice(this.model.resourceList.indexOf(record), 1);
      },
    }
  }
</script>
